package mc.contents.web.listener;

import mc.contents.pojo.persistence.ShopKeyword;
import mc.contents.pojo.view.Rank;
import mc.contents.pojo.view.RankDisplay;
import mc.contents.service.ICrawService;
import mc.contents.web.SourceConfig;
import mc.contents.web.common.*;
import mc.contents.web.request.RankCrawRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 14-12-8.
 */
public class RankAppAsyncListener extends AbstractAsyncListener {
    private static Logger log = LoggerFactory.getLogger( RankAppAsyncListener.class );
    private ICrawService crawService;

    public RankAppAsyncListener( Long id, Long start, ICrawService crawService, String name ) {
        super( id, start, name );
        this.crawService = crawService;
    }

    @Override
    public String handleResult( String errMsg,CommonContext commonContext,long start ) {
        RankCrawRequest request = (RankCrawRequest) commonContext.getCrawRequest();
        List<CrawResult> results = commonContext.getCrawResults();

        ShopKeyword shopKeyword = crawService.getByKeyword(((RankCrawRequest) commonContext.getCrawRequest()).getKeyword());

        Set<Rank> ranks = new HashSet<>(  );
        if( results != null && !results.isEmpty() ){
            ranks = crawService.getRanks( request, results );
        }

        RankDisplay display = new RankDisplay();
        display.setRanks( ranks );
        display.setQueryUrl( buildQueryUrl( request ) );
        display.setDuration( System.currentTimeMillis() - start );
        if( shopKeyword!=null ){
            display.setDealRate(shopKeyword.getDealRate());
            display.setExposure( shopKeyword.getExposure() );
            display.setProductNum( shopKeyword.getProductNum() );
            display.setSearchNum( shopKeyword.getSearchNum() );
        }
        return getJsonStr(display,errMsg);
    }

    private String buildQueryUrl( RankCrawRequest crawRequest ) {
        SourceConfig sourceConfig = SourceConfig.getSourceConfig( crawRequest.getSourceType() );
        String encodeKeyword = getEncodeKeyword( crawRequest.getKeyword(),sourceConfig.getCharset() );
        SimpleDateFormat format = new SimpleDateFormat( "yyyyMMdd" );
        String sourceType = crawRequest.getSourceType();
        String sort = crawRequest.getSortType();
        String sortType = SortMap.getSortType( sort );
        StringBuilder sb = new StringBuilder();
        if("taobao".equals( sourceType )){
            sb.append( "http://s.taobao.com/search?initiative_id=tbindexz_");
            sb.append( format.format( new Date(  ) ) );
            sb.append( "&tab=all&style=grid&q=" );
            sb.append( encodeKeyword );
            sb.append( "&sort=" );
            sb.append( sortType );
            if(sortType.equals( "renqi-desc" )){
                sb.append( "&bcoffset=1" );
            }
            if(sortType.equals( "default" )){
                sb.append( "&bcoffset=-8" );
            }
        }
        if("tmall".equals( sourceType )){
            sb.append( "http://list.tmall.com/search_product.htm?s=0&q=" );
            sb.append( encodeKeyword );
            sb.append( "&sort=" );
            sb.append( sortType );
            sb.append( "&style=g&type=pc" );
        }
        return sb.toString();
    }
    private String getEncodeKeyword( String keyword, String charset ) {
        String encodeKeyword = null;
        try {
            encodeKeyword = URLEncoder.encode( keyword,charset);
        } catch ( UnsupportedEncodingException e ) {
            log.error( keyword + " encode error " );
        }
        return encodeKeyword;
    }
}
